package com.lzs.bootsafety.business.sys.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lzs.bootsafety.business.sys.entity.SysUser;
import com.lzs.bootsafety.business.sys.entity.SysUserPost;
import com.lzs.bootsafety.business.sys.entity.SysUserPwd;
import com.lzs.bootsafety.business.sys.entity.SysUserRole;
import com.lzs.bootsafety.business.sys.mapper.SysUserMapper;
import com.lzs.bootsafety.business.sys.mapper.SysUserPostMapper;
import com.lzs.bootsafety.business.sys.mapper.SysUserRoleMapper;
import com.lzs.bootsafety.business.sys.service.SysUserService;
import com.lzs.bootsafety.common.exception.LzsException;
import com.lzs.bootsafety.common.util.CheckIsNull;
import com.lzs.bootsafety.common.util.PasswordMakeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Service
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private SysUserPostMapper sysUserPostMapper;
    @Override
    public SysUser getUserByName(String username) {
        return sysUserMapper.selectUserByName(username);
    }

    @Override
    public SysUser getByPrimaryKey(Long userId) {
        return sysUserMapper.selectByPrimaryKey(userId);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public int del(Long[] ids) {
        List<Long> userId = new ArrayList<>();
        for (int i = 0; i <ids.length ; i++) {
            userId.add(ids[i]);
        }
        sysUserRoleMapper.deleteUserRoleByUserId(userId);
        sysUserPostMapper.deleteSysUserPost(userId);
        return sysUserMapper.remove(ids);
    }

    @Override
    public PageInfo<SysUser> getUserByWhere(SysUser sysUser) {
        Integer page = sysUser.getPage();
        Integer limit = sysUser.getLimit();
        PageHelper.startPage(page = page == null ? 1 : page,limit = limit == null ? 10 : limit);
        List<SysUser> sysUserList = sysUserMapper.selectUserByWhere(sysUser);
        return new PageInfo<SysUser>(sysUserList);
    }

    @Override
    public List<SysUser> getAllUser() {
        return sysUserMapper.selectAllUser();
    }

    @Override
    public List<SysUser> getUserByUserId(Long[] userIds) {
        return sysUserMapper.selectUserByUserId(userIds);
    }

    /**
     * 添加
     * @param sysUser
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public int addSysUser(SysUser sysUser) {
        int r = sysUserMapper.insertSelective(sysUser);
        addUserRole(sysUser);
        addUserPost(sysUser);
        return r;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public int updateByPrimaryKeySelective(SysUser sysUser) {
        List<Long> userId = new ArrayList<>();
        userId.add(sysUser.getUserId());
        sysUserRoleMapper.deleteUserRoleByUserId(userId);
        sysUserPostMapper.deleteSysUserPost(userId);
        addUserRole(sysUser);
        addUserPost(sysUser);
        return sysUserMapper.updateByPrimaryKeySelective(sysUser);
    }

    /**
     * 验证邮箱唯一性
     * @param email
     * @return
     */
    @Override
    public SysUser checkUserByEmail(String email) {
        return sysUserMapper.verifyUserByEmail(email);
    }

    /**
     * 验证手机号唯一性
     * @param mobile
     * @return
     */
    @Override
    public SysUser checkUserByMobile(String mobile) {
        return sysUserMapper.verifyUserByMobile(mobile);
    }

    @Override
    public int modifyPassword(SysUserPwd sysUserPwd) {
        if (!sysUserPwd.getNewPassword().equals(sysUserPwd.getNewPasswordRepeat())){
            throw new LzsException("新密码不一致");
        }
        SysUser user = sysUserMapper.selectByPrimaryKey(sysUserPwd.getUserId());
        CheckIsNull checkIsNull = new CheckIsNull();
        if(checkIsNull.objCheckIsNull(user)){
            throw new LzsException("数据不能为空");
        }
        if (!user.getPassword().equals(PasswordMakeUtil.getPassword(sysUserPwd.getPassword(),user.getSalt(),8))){
            throw new LzsException("原密码不正确");
        }
        user.setPassword(sysUserPwd.getNewPassword());
        return updateUser(user);
    }
    public int updateUser(SysUser sysUser){
        if (!StringUtils.isEmpty(sysUser.getPassword())){
            sysUser.setPassword(PasswordMakeUtil.getPassword(sysUser.getPassword(),sysUser.getSalt(),8));
        }else{
            sysUser.setPassword(null);
        }
        return sysUserMapper.updateByPrimaryKeySelective(sysUser);
    }

    /**
     * 添加用户角色
     */
    public void addUserRole(SysUser sysUser){
       Long[] roleIds = sysUser.getRoleIds();
       if(roleIds.length > 0){
            List<SysUserRole> sysUserRoles = new ArrayList<>();
           for (Long roleId:roleIds) {
                SysUserRole userRole = new SysUserRole();
                userRole.setRoleId(roleId);
                userRole.setUserId(sysUser.getUserId());
                sysUserRoles.add(userRole);
           }
           if (sysUserRoles.size() > 0){
               sysUserRoleMapper.insertUserRole(sysUserRoles);
           }
       }
    }
    public void addUserPost(SysUser sysUser){
        Long[] postIds = sysUser.getPostIds();
        if(postIds.length > 0){
            List<SysUserPost> sysUserPosts = new ArrayList<>();
            for (Long postId: postIds) {
                SysUserPost sysUserPost = new SysUserPost();
                sysUserPost.setPostId(postId);
                sysUserPost.setUserId(sysUser.getUserId());
                sysUserPosts.add(sysUserPost);
            }
            if(sysUserPosts.size() > 0){
                sysUserPostMapper.insertSysUserPost(sysUserPosts);
            }
        }
    }
}
